package com.bamboo.tool.view.component.dialog;

import com.bamboo.tool.config.BambooToolComponent;
import com.bamboo.tool.constant.StringConstant;
import com.bamboo.tool.db.entity.BambooApiMethod;
import com.bamboo.tool.entity.NoteData;
import com.bamboo.tool.entity.treenode.ProjectNodeInfo;
import com.bamboo.tool.store.StoreService;
import com.bamboo.tool.view.component.tree.ApiTree;
import com.bamboo.tool.view.component.tree.ClassNode;
import com.bamboo.tool.view.component.tree.MethodNode;
import com.bamboo.tool.view.component.tree.ProjectNode;
import com.intellij.openapi.ui.DialogWrapper;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.tree.TreePath;
import java.util.Map;

/**
 * @author EDZ
 */
public class RenameDialog extends DialogWrapper {
    private JPanel mainPanel;
    private JTextField renameField;
    private ApiTree apiTree;

    public RenameDialog(ApiTree apiTree) {
        super(false);
        init();
        this.apiTree = apiTree;
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return mainPanel;
    }

    @Override
    protected void doOKAction() {
        StoreService storeService = BambooToolComponent.getStoreService();
        TreePath path = apiTree.getSelectionPath();
        Object lastPathComponent = path.getLastPathComponent();
        String renameFieldText = renameField.getText();
        if (lastPathComponent instanceof ProjectNode) {
            ProjectNode projectNode = (ProjectNode) lastPathComponent;
            ProjectNodeInfo source = projectNode.getSource();
            source.setName(renameFieldText);
            storeService.renameProject(source.getProjectId(), renameFieldText);
        } else if (lastPathComponent instanceof ClassNode) {
            ClassNode classNode = (ClassNode) lastPathComponent;
            NoteData source = classNode.getSource();
            String classId = source.getClassId();
            source.getPersistenceInfo().setRename(renameFieldText);
            storeService.renameClass(classId, renameFieldText);
        } else if (lastPathComponent instanceof MethodNode) {
            MethodNode methodNode = (MethodNode) lastPathComponent;
            BambooApiMethod method = methodNode.getSource();
            String methodId = method.getMethodId();
            method.getMethodPersistenceInfo().setRename(renameFieldText);
            storeService.renameMethod(methodId, renameFieldText);
        }

        apiTree.startEditingAtPath(path);
        super.doOKAction();
    }
}
